package com.zsc.wxm.ysh.anjo.house.task;

import cn.hutool.core.collection.CollUtil;
import com.zsc.wxm.ysh.anjo.house.cache.AdvertiseCacheService;
import com.zsc.wxm.ysh.anjo.house.model.Advertise;
import com.zsc.wxm.ysh.anjo.house.service.AdvertiseService;
import com.zsc.wxm.ysh.anjo.service.base.enums.resources.AdvertiseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author playmaker
 * @since 2021/3/13 11:52
 */
@Slf4j(topic = "资讯更新状态定时任务")
@Component
public class UpdateAdvertiseStatusTask {

    @Resource
    private AdvertiseService service;

    @Resource
    private AdvertiseCacheService advertiseCacheService;

    @Scheduled(cron = "0 0 0/5 * * ?")
    public void updateStatus() {
        long start = System.currentTimeMillis();
        //获取已过期，还有效的数据
        List<Advertise> list = advertiseCacheService.listByCache()
                .stream()
                .filter(x -> x.getEndTime().toEpochSecond(ZoneOffset.of("+8")) <= LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")))
                .filter(x -> x.getStatus().equals(AdvertiseStatus.VALID.getValue()))
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(list)) {
            log.info("没有可处理的数据...");
        }
        list.forEach(x -> {
            x.setStatus(AdvertiseStatus.NOT_VALID.getValue());
            service.updateById(x);
        });
        log.info("UpdateAdvertiseStatusTask定时任务执行结束，消耗的时间: {}ms", System.currentTimeMillis() - start);
        //清除缓存
        advertiseCacheService.removeByCache();
    }
}
